import { ref, onUnmounted } from 'vue'
import useHotKey from './hotKeys'

export function useBroad() {
  let p2p = null
  let remoteId = null
  const ele = document.documentElement
  const broadKey = ref('')
  const sendMessage = (event, flag) => {
    broadKey.value = event.key
    const params = {
      endpointType: 1,
      events: [
        {
          eventType: 'keyboard',
          timestamp: Math.floor(new Date().getTime() / 1000) + '',
          eventData: JSON.stringify({
            flag,
            code: event.keyCode
          })
        }
      ]
    }
    p2p && p2p.send(remoteId, JSON.stringify(params))
  }

  // 监听键盘按下事件
  const addKeyDown = (event) => {
    sendMessage(event, 4)
  }

  // 监听键盘弹起事件
  const addKeyUp = (event) => {
    sendMessage(event, 0)
  }
  const addBroadEvent = (p2pObj, id) => {
    console.log('监听键盘事件...')
    p2p = p2pObj
    remoteId = id
    ele.addEventListener('keydown', addKeyDown)
    ele.addEventListener('keyup', addKeyUp)
  }
  const removeBroadEvent = () => {
    ele.removeEventListener('keydown', addKeyDown)
    ele.removeEventListener('keyup', addKeyUp)
  }

  // 监听处理浏览器默认按键处理,只有在全屏模式下才有效
  const autoKey = [
    'ctrl+w',
    'ctrl+t',
    'ctrl+n',
    'ctrl+tab',
    'ctrl+shift+tab',
    'ctrl+shift+n',
    ' ctrl+f5',
    ' f5',
    'ctrl+r',
    'ctrl+f',
    'ctrl+f1',
    'ctrl+f2',
    'ctrl+1',
    'ctrl+2'
  ]
  useHotKey(autoKey.join(','), (event) => {
    console.log('监听浏览器默认快捷键...')
    event.preventDefault()
  })

  // 移除键盘监听事件
  onUnmounted(() => {
    try {
      removeBroadEvent()
    } catch (err) {
      console.log(err)
    }
  })

  return { broadKey, addBroadEvent, removeBroadEvent }
}
